package com.example.user.service.domain.valueobject;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 *
 * @param encryptedValue 密码 明文密码还是密文密码？->密文
 */
@Slf4j
public record Password(String encryptedValue) {
    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    public static Password fromRaw(String rawPassword) {
        if (rawPassword == null || rawPassword.length() < 6) {
            throw new RuntimeException("密码长度至少6位");
        }

        log.info("密码明文: {},密码密文{}", rawPassword,encoder.encode(rawPassword));
        return new Password(encoder.encode(rawPassword));
    }

    /**
     * 从已加密的密码创建Password对象
     * 用于从持久化层恢复数据
     */
    public static Password fromEncrypted(String encryptedPassword) {
        return new Password(encryptedPassword);
    }

    public boolean verify(String rawPassword) {
        return encoder.matches(rawPassword, encryptedValue);
    }

    // 用于密码重置
    public static Password of(String encryptedValue) {
        return new Password(encryptedValue);
    }
}
